//
//  LTTicketTableController.m
//  LocalTravelIPhone
//
//  Created by zheng ji on 14-3-30.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "LTTicketTableController.h"

@interface LTTicketTableController ()
{
    UIActivityIndicatorView *_activityView;
    UILabel* _loadMoreTip;
    NSMutableDictionary* _dictAllPolicy;
    NSArray* _priceArray;
    NSString* _sceneryId;
}
@end

@implementation LTTicketTableController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _sceneryId=[self.dictScenery objectForKey:@"sceneryId"];
    self.navigationItem.title=[self.dictScenery objectForKey:@"sceneryName"];

    [self.tableView registerNib:[UINib nibWithNibName:@"TicketTableCell" bundle:nil] forCellReuseIdentifier:@"TicketTableCell"];
    
    [self createActivityIndicatorView];
    [NSThread detachNewThreadSelector:@selector(loadTicketData) toTarget:self withObject:nil];
}
-(void)loadTicketData{
    if(self.dictScenery==nil)return ;
 
    NSString* localJson=[NSString stringWithFormat:@"%@/%@_tickets.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    
    if([CommonConfigUtil existFileWithLocalPath:localJson]){
        //从本地读取
        NSDictionary *fileAttributes=[[NSFileManager defaultManager] attributesOfItemAtPath:localJson error:nil];
        if(nil!=fileAttributes){
            NSDate *fileModifyDate=  [fileAttributes objectForKey:NSFileModificationDate];
            NSTimeInterval timesecod= [[NSDate date] timeIntervalSinceDate:fileModifyDate];
            // NSLog(@"timesecod:%f",timesecod);
            //缓存7天
            if(nil!=fileModifyDate && timesecod>[CommonConfigUtil getRoladTicketDataTimeSecond]){
                
                //从网络获取
                [self loadTicketDataFromNet];
                
            }else{
                //从本地获取
                [self loadTicketDataFromLocal];
            }
        }else{
            //从网络获取
            [self loadTicketDataFromNet];
        }
        
        
    }else{
        //从网络读取
        [self loadTicketDataFromNet];
    }
    
    [self performSelectorOnMainThread:@selector(reloadTicketTableView) withObject:nil waitUntilDone:NO];
}
-(void)reloadTicketTableView{
     _priceArray=[_dictAllPolicy objectForKey:@"policy"];
    [self.tableView reloadData];
    [self stopActivityIndicatorView];
}

-(void)loadTicketDataFromLocal{
    NSString* localJson=[NSString stringWithFormat:@"%@/%@_tickets.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    NSData* jsonData=[NSData dataWithContentsOfFile:localJson];
    if(jsonData !=nil){
        NSError* error;
         _dictAllPolicy=  [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        if (error || _dictAllPolicy==nil ) {
            [self loadTicketDataFromNet];//从网络获取
        }
    }
    
}
-(void)loadTicketDataFromNet{
    
    //NSString* _sceneryId=[self.dictScenery objectForKey:@"sceneryId"];
    
    
    NSString* xmlData=[LocalTravelRequest getSceneryPrice:_sceneryId showDetail:1 useCache:0];
    
    //NSLog(@"%@",xmlData);
    SceneryPriceParse* parse=[[SceneryPriceParse alloc]initWithXmlData:xmlData];
    _dictAllPolicy=[parse getScenaryPriceList];
    _priceArray=[_dictAllPolicy objectForKey:@"policy"];
    parse=nil;
    xmlData=nil;
    
    

    [NSThread detachNewThreadSelector:@selector(writeTicketToLocal:) toTarget:self withObject:_dictAllPolicy];
    
    //[self stopActivityIndicatorView];
}
-(void)writeTicketToLocal:(NSDictionary*)dict{
    if(dict==nil || dict.count==0)return ;
    NSString* localCityJson=[NSString stringWithFormat:@"%@/%@_tickets.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    
    [CommonConfigUtil writeJsonToLocal:dict localFile:localCityJson];
    
}
-(void)stopActivityIndicatorView{
    [_activityView stopAnimating];
    [_activityView removeFromSuperview];
    _loadMoreTip.hidden=YES;
    [_loadMoreTip removeFromSuperview];
    
}
-(void)createActivityIndicatorView{
    _activityView=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _activityView.hidesWhenStopped=YES;
    CGRect activityFrame=_activityView.frame;
    activityFrame.origin.x=self.view.frame.size.width/2-50;
    activityFrame.origin.y=self.view.frame.size.height/2-100;
    
    [_activityView setFrame:activityFrame];
    
    _activityView.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
    
    
    
    _loadMoreTip=[[UILabel alloc] initWithFrame:CGRectMake(activityFrame.origin.x+30, activityFrame.origin.y+5, 100, 20)];
    
    _loadMoreTip.textAlignment=NSTextAlignmentCenter;
    
    _loadMoreTip.text=@"正在加载数据";
    _loadMoreTip.textColor=[UIColor redColor];
    _loadMoreTip.font=[UIFont systemFontOfSize:16];
    _loadMoreTip.backgroundColor=[UIColor clearColor];
    
    [self.view addSubview:_activityView];
    [self.view addSubview:_loadMoreTip];
    [_activityView startAnimating];
    _activityView.hidden=NO;
    _loadMoreTip.hidden=NO;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 113;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(_priceArray !=nil) return _priceArray.count;
    
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"TicketOrderSegue" sender:indexPath];
    
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    NSIndexPath* indexPath=sender;
    
     NSDictionary* dictTicket=[_priceArray objectAtIndex:indexPath.row];
    
    NSMutableDictionary* dictParam=[NSMutableDictionary dictionary];
    [dictParam setObject:_sceneryId forKey:@"sceneryId"];
    
    [dictParam setObject:[_dictAllPolicy objectForKey:@"day"] forKey:@"day"];
    [dictParam setObject:[_dictAllPolicy objectForKey:@"time"] forKey:@"time"];
    NSString* useCard=[_dictAllPolicy objectForKey:@"useCard"];
    
    if(useCard==nil)useCard=@"0";
    
    [dictParam setObject:useCard forKey:@"useCard"];
     
    
    [dictParam setObject:dictTicket forKey:@"ticket"];
    
    LTTicketOrderController* orderCtrl=segue.destinationViewController;
    orderCtrl.dictParam=dictParam;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TicketTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TicketTableCell" forIndexPath:indexPath];
    
    if(_priceArray !=nil && _priceArray.count>indexPath.row){
        NSDictionary* dict=[_priceArray objectAtIndex:indexPath.row];
        
        cell.lblPolicyName.text=[dict objectForKey:@"policyName"];
        
        //cell.lblPrice.isWithStrikeThrough=YES;
        cell.lblPrice.text=[NSString stringWithFormat:@"票面价：%@",[dict objectForKey:@"price"]];
        cell.lblTCPrice.textColor=[UIColor redColor];
        cell.lblTCPrice.text=[NSString stringWithFormat:@"同程价：%@",[dict objectForKey:@"tcPrice"]];
        NSString* pMode=[dict objectForKey:@"pMode"];
        if(pMode !=nil){
            if([pMode isEqualToString:@"0"]){
                cell.lblPayMode.text=@"景区现付";
            }else if([pMode isEqualToString:@"1"]){
                cell.lblPayMode.text=@"在线支付";
            }else{
                cell.lblPayMode.text=@"其他方式";
            }
        }
        
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }
    
    return cell;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
